package com.education.api.indicator;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 自定义健康检查逻辑
 * DataSourceHealthIndicator 来避免调用 isValid() 方法，改用 SQL 查询判断连接有效性。
 */
@Component
public class CustomDataSourceHealthIndicator implements HealthIndicator {
    private final DataSource dataSource;

    public CustomDataSourceHealthIndicator(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public Health health() {
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery("SELECT 1")) {

            if (resultSet.next() && resultSet.getInt(1) == 1) {
                return Health.up().build();
            } else {
                return Health.down().withDetail("Error", "Database query failed").build();
            }
        } catch (Exception e) {
            return Health.down(e).build();
        }
    }
}
